<template>
  <a-select
      v-model:value="checkTags"
      mode="tags"
      style="width: 100%"
      @click="drawerTag = true"
      :options="tags.map(item => ({ label: item.name, value: item.id }))"
      placeholder="请选择标签"
  ></a-select>
  <a-drawer
      v-model:visible="drawerTag"
      class="custom-class"
      style="color: red"
      title="标签选择"
      placement="right"
      @after-visible-change="afterVisibleChange"
  >
    <template v-for="(tag, _index) in tags" :key="_index">
      <div style="display: inline-block; margin-bottom: 10px;">
        <a-tag :closable="true" :visible="true" :color="tag.checked ? 'blue' : ''" @click="tagClick(tag)" @close="remove(tag.id)">
          {{ tag.name }}
        </a-tag>
      </div>
    </template>
    <a-input
        v-if="inputVisible"
        ref="inputRef"
        v-model:value="inputValue"
        size="small"
        :maxlength="45"
        :style="{ width: '78px' }"
        @blur="handleInputConfirm"
        @keyup.enter="handleInputConfirm"
    />
    <a-tag v-else style="background: #fff; border-style: dashed" @click="showInput">
      <plus-outlined />
      New Tag
    </a-tag>
  </a-drawer>
</template>
<script setup>
import {ref, toRefs, nextTick, defineProps} from 'vue';
import useTags from "./useTags";
import { PlusOutlined } from '@ant-design/icons-vue';

const props = defineProps({
  checks: {
    type: Array,
    default: () => []
  }
})

const emit = defineEmits(['update:checks'])

const { tags, remove, check, checkTags, add, addWatchCheck } = useTags(props.checks);

addWatchCheck(val => {
  emit('update:checks', val);
})

const inputRef = ref();
const inputVisible = ref(false);
const inputValue = ref('');
const drawerTag = ref(false);

const showInput = () => {
  inputVisible.value = true;
  nextTick(() => {
    inputRef.value.focus();
  })
};

const handleInputConfirm = () => {
  add(inputValue.value);
  inputValue.value = '';
  inputVisible.value = false;
};

const tagClick = check;
</script>

